package com.seari.controller;

import com.seari.bean.*;
import com.seari.pojo.DataGridBean;
import com.seari.pojo.MessageBean;
import com.seari.pojo.QueryUser;
import com.seari.service.EquipmentService;
import com.seari.service.UserService;
import com.seari.utils.DateUtil;
import com.seari.utils.ParseUtils;
import com.seari.utils.StringHelper;
import com.seari.utils.Tools;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@RequestMapping("et")
public class EquipmentController {
    @Autowired
    private EquipmentService equipmentService;
    @Autowired
    private UserService userService;
    private Logger log = LoggerFactory.getLogger(this.getClass());
    @RequestMapping("/getFMcByParams")
    @ResponseBody
    public Map<String, Object> getFMcByParams(HttpServletRequest req) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        DataGridBean<MaterialCaregory> grid = new DataGridBean<MaterialCaregory>();
        String fMcRemark = req.getParameter("fMcRemark");
        String fStatus = req.getParameter("fStatus");
        String fParent = req.getParameter("fParent");
        MaterialCaregory mc = new MaterialCaregory();
        if (StringUtils.isNotBlank(fMcRemark)) {
            mc.setfMcRemark(fMcRemark);
        }
        if (StringUtils.isNotBlank(fStatus)) {
            mc.setfStatus(fStatus);
        }
        if (StringUtils.isNotBlank(fParent)) {
            mc.setfParent(fParent);
        }

        List<MaterialCaregory> materialCaregorys = equipmentService.getFMcByParams(mc);
        grid.setRows(materialCaregorys);

//        if (materialCaregorys != null && materialCaregorys.size() > 0) {
//            String fLevel = materialCaregorys.get(0).getfLevel();
//            resultMap.put("fLevel", fLevel);
//        } else {
//            MaterialCaregory materialCategory = new MaterialCaregory();
//            materialCategory.setfMcId(fParent);
//            materialCategory = equipmentService.getFMcByFMcId(materialCategory);
//            if (materialCategory != null) {
//                resultMap.put("fHasChild", materialCategory.getfHasChild());
//            }
//        }
        resultMap.put("grid", grid);
        return resultMap;
    }

    @RequestMapping("/getTitle")
    @ResponseBody
    public Map<String, Object> getTitle(HttpServletRequest req) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String title = "";
        String fMcId = req.getParameter("fMcId");
        MaterialCaregory mc = new MaterialCaregory();
        if (StringUtils.isNotBlank(fMcId)) {
            mc.setfMcId(fMcId);
            List<MaterialCaregory> materialCaregorys = equipmentService.getFMcTree(mc);
            if (materialCaregorys != null && materialCaregorys.size() > 0) {
                MaterialCaregory materialCaregory = materialCaregorys.get(0);
                String fMcShowName1 = materialCaregory.getfMcShowName();
                title = fMcShowName1;
                String fMcShowName2 = "";
                String fMcShowName3 = "";
                if (materialCaregory.getChildren() != null && materialCaregory.getChildren().size() > 0) {
                    MaterialCaregory materialCaregoryChild = materialCaregory.getChildren().get(0);
                    fMcShowName2 = materialCaregoryChild.getfMcShowName();
                    title = title + ">" + fMcShowName2;
                    resultMap.put("fMcShowName", fMcShowName2);
                    if (materialCaregoryChild.getChildren() != null && materialCaregoryChild.getChildren().size() > 0) {
                        fMcShowName3 = materialCaregoryChild.getChildren().get(0).getfMcShowName();
                        title = title + ">" + fMcShowName3;
                        resultMap.put("fMcShowName", fMcShowName3);
                    }
                } else {
                    resultMap.put("fMcShowName", title);
                }
            } else {
                MaterialCaregory materialCaregory = equipmentService.getFMcByFMcId(mc);
                title = materialCaregory.getfMcShowName();
                resultMap.put("fMcShowName", title);
            }
        }

        resultMap.put("title", title);
        return resultMap;
    }

    @RequestMapping("/getStationList")
    @ResponseBody
    public Map<String, Object> getStationList(HttpServletRequest req) {
        Map<String, Object> resultMap = new HashMap<String, Object>();

        List<Station> stationList = equipmentService.getStationByParam(new Station());
        if (stationList != null && stationList.size() > 0) {
            resultMap.put("stationList", stationList);
            resultMap.put("stationSize", stationList.size());
            resultMap.put("code", "success");
        } else {
            resultMap.put("code", "failed");
        }

        return resultMap;
    }

    @RequestMapping("/getTableCode")
    @ResponseBody
    public Map<String, Object> getTableCode(HttpServletRequest req) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String fMcId = req.getParameter("fMcId");
        MaterialCaregoryAttr mcAttr = new MaterialCaregoryAttr();
        if (StringUtils.isNotBlank(fMcId)) {
            mcAttr.setfMcId(fMcId);
            mcAttr.setfCaEnabled("1");
            List<MaterialCaregoryAttr> mcAttrList = equipmentService.getFMcAttrByParams(mcAttr);
            if (mcAttrList != null && mcAttrList.size() > 0) {
                resultMap.put("code", "success");
                resultMap.put("mcAttrList", mcAttrList);
            } else {
                resultMap.put("code", "failed");
            }
            List<Station> stationList = equipmentService.getStationByParam(new Station());
            if (stationList != null && stationList.size() > 0) {
                resultMap.put("stationList", stationList);
                resultMap.put("stationSize", stationList.size());
            }

            MaterialCaregory mc = new MaterialCaregory();
            mc.setfMcId(fMcId);
            List<MaterialCaregory> materialCaregorys = equipmentService.getFMcTree(mc);
            if (materialCaregorys != null && materialCaregorys.size() > 0) {
                MaterialCaregory materialCaregory = materialCaregorys.get(0);
                String fMcShowName2 = "";
                String fMcShowName3 = "";
                if (materialCaregory.getChildren() != null && materialCaregory.getChildren().size() > 0) {
                    MaterialCaregory materialCaregoryChild = materialCaregory.getChildren().get(0);
                    fMcShowName2 = materialCaregoryChild.getfMcShowName();
                    resultMap.put("zcTypeId", fMcShowName2);
                    if (materialCaregoryChild.getChildren() != null && materialCaregoryChild.getChildren().size() > 0) {
                        fMcShowName3 = materialCaregoryChild.getChildren().get(0).getfMcShowName();
                        resultMap.put("zcSubTypeId", fMcShowName3);
                    }
                }
            }

            List<Map<String, String>> lineList = equipmentService.getLineList(null);
            if (lineList != null && lineList.size() > 0) {
                resultMap.put("lineId", lineList.get(0).get("lineId"));
                resultMap.put("lineList", lineList);
            }

            String uid = ParseUtils.getUidFromToken(req, userService);
            Map<String, String> param = new HashMap<>();
            param.put("USER_ID", uid);
            QueryUser qu = new QueryUser();
            qu.setUid(Integer.parseInt(uid));
            List<User> userByUid = userService.getUserByUid(qu);
            resultMap.put("userId", uid);
            if (userByUid != null) {
                resultMap.put("userName", String.valueOf(userByUid.get(0).getUserName()));
            }
            resultMap.put("createTime", Tools.date2Str(new Date()));
        } else {
            resultMap.put("code", "failed");
        }
        return resultMap;
    }

    @RequestMapping("/getStationByStationId")
    @ResponseBody
    public Map<String, Object> getStationByStationId(HttpServletRequest req) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String stationId = req.getParameter("stationId");
        Station station = new Station();
        if (StringUtils.isNotBlank(stationId)) {
            station.setStationId(stationId);
            List<Station> stationList = equipmentService.getStationByParam(station);
            if (stationList != null && stationList.size() > 0) {
                resultMap.put("stationList", stationList);
                resultMap.put("stationSize", stationList.size());
            }
        } else {
            resultMap.put("code", "failed");
        }
        return resultMap;
    }

    @RequestMapping("/getTableCodeAndValue")
    @ResponseBody
    public Map<String, Object> getTableCodeAndValue(HttpServletRequest req) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String fMcId = req.getParameter("fMcId");
        String fProductId = req.getParameter("fProductId");
        MaterialCaregoryAttr mcAttr = new MaterialCaregoryAttr();
        if (StringUtils.isNotBlank(fProductId)) {
            mcAttr.setfProductId(fProductId);
            if (StringUtils.isBlank(fMcId)) {
                Product product = new Product();
                product.setfProductId(fProductId);
                List<Product> productList = equipmentService.getProductById(product);
                if (productList != null && productList.size() > 0) {
                    fMcId = productList.get(0).getfMcId();
                }
            }
            mcAttr.setfMcId(fMcId);
        }
        List<MaterialCaregoryAttr> mcAttrList = equipmentService.getAttrAndValueByFMcId(mcAttr);
        if (mcAttrList != null && mcAttrList.size() > 0) {
            resultMap.put("code", "success");
            resultMap.put("mcAttrList", mcAttrList);
        } else {
            resultMap.put("code", "failed");
        }

        List<Map<String, String>> lineList = equipmentService.getLineList(null);
        if (lineList != null && lineList.size() > 0) {
            resultMap.put("lineId", lineList.get(0).get("lineId"));
            resultMap.put("lineList", lineList);
        }

        List<Station> stationList = equipmentService.getStationByParam(new Station());
        if (stationList != null && stationList.size() > 0) {
            resultMap.put("stationList", stationList);
        }
        return resultMap;
    }

    @RequestMapping("saveAttrValue")
    @ResponseBody
    public MessageBean saveAttrValue(HttpServletRequest request) {
        MessageBean mb = new MessageBean();
        //获取user  验证token是否有权限
//        String userId = ParseUtils.getUidFromToken(request, userService);
//        if (userId == null||userId=="") {
//            mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
//            mb.setMessage("没有权限");
//            return mb;
//        }
        //获取请求参数 fMcId
//        String fMcId = request.getParameter("fMcId");
//        //判断fMcId
//        if (StringUtils.isBlank(fMcId)) {
//            mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
//            mb.setMessage("表单信息不完整！");
//            return mb;
//        }
        Equipment equipment = new Equipment();
        equipment.setDomain(request.getParameter("domain"));
        equipment.setSystem_name(request.getParameter("system_name"));
        String et_name = request.getParameter("et_name");
        equipment.setEt_name(et_name);
        equipment.setEvent_name(et_name);
        equipment.setEt_code(request.getParameter("et_code"));
        equipment.setEt_model(request.getParameter("et_model"));
        equipment.setStation_name(request.getParameter("station_name"));
        equipment.setLine_id(Integer.valueOf(request.getParameter("line_id")));
        equipment.setEt_supplier(request.getParameter("et_supplier"));
        equipment.setEt_producer(request.getParameter("et_producer"));
        equipment.setDate_of_production(DateUtil.stringtoDate(request.getParameter("date_of_production"),DateUtil.LONG_DATE_FORMAT));
        equipment.setGuarantee_period(DateUtil.stringtoDate(request.getParameter("guarantee_period"),DateUtil.LONG_DATE_FORMAT));
        equipment.setSerial_num(request.getParameter("serial_num"));
        equipment.setInstall_location(request.getParameter("install_location"));
        equipment.setInstall_date(DateUtil.stringtoDate(request.getParameter("install_date"),DateUtil.LONG_DATE_FORMAT));
        equipment.setProfessional_id(request.getParameter("professional_id"));
        equipment.setOwner(request.getParameter("owner"));
        equipment.setVoltage(request.getParameter("voltage"));
        equipment.setPower(request.getParameter("power"));
        equipment.setLife(request.getParameter("life"));
        String is_plan = request.getParameter("is_plan");
        char is_plan_ts = 0;
        if (is_plan != null) {
            if (is_plan.equals("是")||is_plan == "是"||is_plan=="1"||is_plan.equals("1")){
                is_plan_ts = '1';
                String maintain_frist_time = request.getParameter("maintain_frist_time");
                if (maintain_frist_time != null||maintain_frist_time != "") {
                    equipment.setMaintain_frist_time(DateUtil.stringtoDate(maintain_frist_time,DateUtil.LONG_DATE_FORMAT));
                }else{
                    mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
                    mb.setMessage("是否取消计划维修？原因：首次维修时间为空.....");
                    return mb;
                }
                String maintain_this_time = request.getParameter("maintain_this_time");
                if (maintain_this_time != null||maintain_this_time != "") {
                    equipment.setMaintain_frist_time(DateUtil.stringtoDate(maintain_this_time,DateUtil.LONG_DATE_FORMAT));
                }else{
                    mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
                    mb.setMessage("是否取消计划维修？原因：本次维修时间为空.....");
                    return mb;
                }
                String maintain_next_time = request.getParameter("maintain_next_time");
                if (maintain_next_time != null||maintain_next_time != "") {
                    equipment.setMaintain_frist_time(DateUtil.stringtoDate(maintain_next_time,DateUtil.LONG_DATE_FORMAT));
                }else{
                    mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
                    mb.setMessage("是否取消计划维修？原因：下次维修时间为空.....");
                    return mb;
                }
                String interval_day = request.getParameter("interval_day");
                if (interval_day != null&&interval_day!=""){
                    equipment.setInterval_day(Integer.valueOf(interval_day));
                }else{
                    mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
                    mb.setMessage("是否取消计划维修？原因：间隔天数为空.....");
                    return mb;
                }
                String maintain_next_day = request.getParameter("maintain_next_day");
                if (maintain_next_day != null||maintain_next_day!=""){
                    equipment.setInterval_day(Integer.valueOf(maintain_next_day));
                }else{
                    mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
                    mb.setMessage("是否取消计划维修？原因：距离下次维护计划时间（天）为空.....");
                    return mb;
                }
            }else if(is_plan.equals("否")||is_plan == "否"||is_plan=="0"||is_plan.equals("0")){
                is_plan_ts = '0';
            }else{
                mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
                mb.setMessage("请选择是否要计划维修....");
                return mb;
            }
        }
        equipment.setIs_plan(is_plan_ts);
        String et_type = request.getParameter("et_type");
        equipment.setEvent_type(et_type);
        equipment.setEt_type(et_type);
        equipment.setEt_comment(request.getParameter("et_comment"));
        equipment.setMaintain_way(request.getParameter("maintain_way"));

//        equipment.setCreated_id("");
//        equipment.setCreated_name("");
        equipment.setCreated_time(getCurrDate());
        int result = 0;
        if(is_plan.equals("是")||is_plan == "是"||is_plan=="1"||is_plan.equals("1")){
            equipmentService.saveEtInfoPlan(equipment);
            result = equipmentService.saveEtInfo(equipment);
        }else{
            result = equipmentService.saveEtInfo(equipment);
        }
        if(result>0){
            mb.setCode(StringHelper.MESSAGE_TYPE_SUCCESS);
            mb.setMessage("当前设备录入成功....");
        }else{
            mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
            mb.setMessage("当前设备录入失败....");
        }
        return mb;
    }
    /**
     * 获取当前时间的指定格式
     */
    public static Date getCurrDate() {
        try {
            URL url = new URL("http://time.tianqi.com/%7B:APP_HOST%7D/");
            URLConnection uc = url.openConnection();
            uc.connect(); //发出连接
            long ld=uc.getDate(); //取得网站日期时间
            Date date=new Date(ld); //转换为标准时间对象
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DateUtil.FORMAT_ONE);
            String format = simpleDateFormat.format(date);
            return simpleDateFormat.parse(format);
        } catch (IOException e) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DateUtil.FORMAT_ONE);
            return DateUtil.stringtoDate(simpleDateFormat.format(new Date()),DateUtil.FORMAT_ONE);
        } catch (ParseException e) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DateUtil.FORMAT_ONE);
            return DateUtil.stringtoDate(simpleDateFormat.format(new Date()),DateUtil.FORMAT_ONE);
        }
    }

    /**
     * 下载资材导入模板。
     *
     * @param response
     * @throws Exception
     * @see
     */
    @RequestMapping(value = "/downloadCateTemplate")
    public void downloadCateTemplate(HttpServletRequest request, HttpServletResponse response) {
        String path = "/static/ExcelModel.xls";
        String fileName = path.substring(path.lastIndexOf("/") + 1);
        try {
            downloadExcel(response, path, fileName);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void downloadExcel(HttpServletResponse response, String path, String fileName) throws IOException {
        /** 将文件名称进行编码 */
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setContentType("content-type:octet-stream");
        /** 读取服务器端模板文件*/
        InputStream inputStream = EquipmentController.class.getResourceAsStream(path);

        /** 将流中内容写出去 .*/
        OutputStream outputStream = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        inputStream.close();
        outputStream.close();
    }

    @SuppressWarnings("resource")
    @RequestMapping(value = "/importProduct")
    @ResponseBody
    public MessageBean importProduct(@RequestParam(value = "file") MultipartFile file,
                                             HttpServletRequest request, HttpServletResponse response) {
        MessageBean mb = new MessageBean();
        try {
            String msgResult = "未知原因....";
            InputStream in = file.getInputStream();
            HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(in));
//            String userId = ParseUtils.getUidFromToken(request, userService);
            HSSFSheet sheet = wb.getSheetAt(0);// 获取数据页
            int totalRows = sheet.getLastRowNum();// 最后一行数据的行号
            HSSFRow row = sheet.getRow(0);//获取字段行
            short lastCellNum = row.getLastCellNum();//获取最后一列数据
            int rowNum = 1;
            String str = "";
            if(totalRows>=rowNum){
                List<Equipment> equipments = new ArrayList<>();
                for (int i = rowNum; i <= totalRows; i++) {
                    Equipment equipment = new Equipment();
                    HSSFRow row1 = sheet.getRow(i);
                    for (int j = 0;j<lastCellNum;j++){
                        try {
                            HSSFCell cell = row1.getCell(j);
                            if(j>=25){
                                if (cell == null) {
                                    break;
                                }
                            }
                            DecimalFormat df = new DecimalFormat("#");
                            switch (cell.getCellType()) {
                                case HSSFCell.CELL_TYPE_NUMERIC:
                                    if(HSSFDateUtil.isCellDateFormatted(cell)){//like12 add,20180622,支持日期格式
                                        Date d = cell.getDateCellValue();
                                        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//HH:mm:ss
                                        str = dateFormat.format(d);
                                    } else {//数字
                                        str = df.format(cell.getNumericCellValue());
                                    }
                                    break;
                                case HSSFCell.CELL_TYPE_STRING:
                                    str = cell.getRichStringCellValue().getString().trim();
                                    break;
                                case HSSFCell.CELL_TYPE_BOOLEAN:
                                    str = String.valueOf(cell.getBooleanCellValue()).trim();
                                    break;
                                case HSSFCell.CELL_TYPE_FORMULA:
                                    str = cell.getCellFormula();
                                    break;
                                default:
                                    str = "";
                            }
                        }catch (NullPointerException e){
                            msgResult = "第"+(i+1)+"行第"+(j+1)+"列没有数据....";
                            str="";
                            log.error(msgResult);
                        }catch (Exception e) {
                            e.printStackTrace();
                            msgResult = "第" + (i+1) + "行第" +(j+1) + "列数据读取失败，原因："+e.getMessage();
                            str="";
                            log.error(msgResult);
                        }
                        try {
                            String cell = row.getCell(j).toString().trim();
                            switch (cell) {
                                case "资材编号":
                                    equipment.setEt_code(str);
                                    break;
                                case "资材名称":
                                    equipment.setEvent_name(str);
                                    equipment.setEt_name(str);
                                    break;
                                case "资材类型":
                                    equipment.setEvent_type(str);
                                    equipment.setEt_type(str);
                                    break;
                                case "资材描述":
                                    equipment.setEt_comment(str);
                                    break;
                                case "资材大类编号":
                                    equipment.setDomain(str);
                                    break;
                                case "资材小类编号":
                                    equipment.setSystem_name(str);
                                    break;
                                case "创建人编号":
                                    equipment.setCreated_id(str);
                                    break;
                                case "创建人姓名":
                                    equipment.setCreated_name(str);
                                    break;
                                case "创建时间":
                                    Date date = DateUtil.stringtoDate(str, DateUtil.FORMAT_ONE);
                                    equipment.setCreated_time(date);
                                    break;
                                case "所属单位":
                                    equipment.setOwner(str);
                                    break;
                                case "规格型号":
                                    equipment.setEt_model(str);
                                    break;
                                case "供应商":
                                    equipment.setEt_supplier(str);
                                    break;
                                case "制作商":
                                    equipment.setEt_producer(str);
                                    break;
                                case "出厂日期":
                                    Date productionDate = DateUtil.stringtoDate(str, DateUtil.FORMAT_ONE);
                                    equipment.setDate_of_production(productionDate);
                                    break;
                                case "保修期至":
                                    Date guaranteeDate = DateUtil.stringtoDate(str, DateUtil.FORMAT_ONE);
                                    equipment.setGuarantee_period(guaranteeDate);
                                    break;
                                case "产品序列号":
                                    equipment.setSerial_num(str);
                                    break;
                                case "专业类别编号":
                                    equipment.setProfessional_id(str);
                                    break;
                                case "额定电压":
                                    equipment.setVoltage(str);
                                    break;
                                case "额定功率":
                                    equipment.setPower(str);
                                    break;
                                case "使用寿命":
                                    equipment.setLife(str);
                                    break;
                                case "线路编号":
                                    Integer line_id = Integer.valueOf(str);
                                    equipment.setLine_id(line_id);
                                    break;
                                case "所属站点":
                                    equipment.setStation_name(str);
                                    break;
                                case "安装位置":
                                    equipment.setInstall_location(str);
                                    break;
                                case "安装日期":
                                    Date installDate = DateUtil.stringtoDate(str, DateUtil.FORMAT_ONE);
                                    equipment.setInstall_date(installDate);
                                    break;
                                case "是否维护计划":
                                    char is_plan = '0';
                                    if(str.equals("是")||str=="是"){
                                        is_plan='1';
                                    }else if(str.equals("否")||str=="否"){
                                        is_plan='0';
                                    }
                                    equipment.setIs_plan(is_plan);
                                    break;
                                case "首次维修计划日期":
                                    Date fristDate = DateUtil.stringtoDate(str, DateUtil.FORMAT_ONE);
                                    equipment.setMaintain_frist_time(fristDate);
                                    break;
                                case "本次维护计划日期":
                                    Date thisDate = DateUtil.stringtoDate(str, DateUtil.FORMAT_ONE);
                                    equipment.setMaintain_this_time(thisDate);
                                    break;
                                case "预计下次维护计划日期":
                                    Date nextDate = DateUtil.stringtoDate(str, DateUtil.FORMAT_ONE);
                                    equipment.setMaintain_next_time(nextDate);
//                                    char is_plans = 1;
//                                    equipment.setIs_plan(is_plans);
                                    break;
                                case "距离下次维护计划时间（天）":
                                    String regEx="[^0-9]";
                                    Pattern p = Pattern.compile(regEx);
                                    Matcher m = p.matcher(str);
                                    Integer trim = Integer.valueOf(m.replaceAll("").trim());
                                    equipment.setMaintain_next_day(trim);
                                    char statu;
                                    if(trim==0){
                                        statu = 1;
                                        equipment.setStatu(statu);
                                    }else if(trim>0){
                                        statu=0;
                                        equipment.setStatu(statu);
                                    }
                                    break;
                                case "维修间隔天数":
                                    Integer intervalDay = Integer.valueOf(str);
                                    equipment.setInterval_day(intervalDay);
                                    break;
                                default:
                                    msgResult = "ExcelModel格式不匹配，第"+(i+1)+"行第"+(j+1)+"列";
                                    log.error(msgResult);
                            }
                        }catch (NullPointerException e){
                            msgResult = "标题行第"+(j+1)+"列没有数据....";
                            str="";
                            log.error(msgResult);
                        }catch (Exception e) {
                            msgResult = "标题行第" + (j+1) + "列数据读取失败，原因："+e.getMessage();
                            str="";
                            log.error(msgResult);
                        }
                    }
                    equipments.add(equipment);
                }
                //Service
                int info = equipmentService.importEtInfo(equipments);
                int infoPlan = equipmentService.importEtInfoPlan(equipments);
                if (infoPlan>0){info = info+equipmentService.importEtInfo(equipments);}
                if(info>0){
                    mb.setCode(StringHelper.MESSAGE_TYPE_SUCCESS);
                    mb.setMessage("导入成功,导入数量："+(info));
                }else {
                    mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
                    mb.setMessage("导入失败原因："+msgResult);
                }
            }else{
                mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
                mb.setMessage("导入失败原因：Excel数据为空....");
            }
        } catch (IOException e) {
            log.error("IOException...."+e.getMessage());
        }
        return mb;
    }
}
